package com.oa.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oa.common.result.Result;
import com.oa.common.result.SystemCode;
import jdk.jfr.ContentType;
import org.apache.commons.lang3.CharSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.digester.DocumentProperties;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;


/**
 * 复合型登录成功执行器
 *
 * @author cuichao
 */
public class ComplexAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    protected final Log logger = LogFactory.getLog(this.getClass());
    private final ObjectMapper mapper = new ObjectMapper();

    /**
     * 请求缓存
     */
    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {

        String accept = request.getHeader(HttpHeaders.ACCEPT);


        boolean isJsonAccept = StringUtils.hasText(accept) && accept.contains(MediaType.APPLICATION_JSON_VALUE);
        boolean isJsonResponse = StringUtils.hasText(request.getParameter("type")) && "json".equals(request.getParameter("type"));

        if (isJsonAccept || isJsonResponse) {
            if(!response.isCommitted()){
                response.setCharacterEncoding("UTF-8");
                response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
                Result ok = Result.success("ok");
                mapper.writeValue(response.getWriter(),ok);
            }
            return;
        }

        defaultSuccessProcessor(request, response, authentication);
    }


    /**
     * 默认的成功执行器
     *
     * @param request
     * @param response
     * @param authentication
     * @throws ServletException
     * @throws IOException
     */
    protected void defaultSuccessProcessor(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {

        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest == null) {
            super.onAuthenticationSuccess(request, response, authentication);
            return;
        }
        String targetUrlParameter = getTargetUrlParameter();

        if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);
            return;
        }
        clearAuthenticationAttributes(request);

        String targetUrl = savedRequest.getRedirectUrl();
        logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
        getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }


    public void setRequestCache(RequestCache requestCache) {
        this.requestCache = requestCache;
    }
}
